/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DateDialog.java
 *
 * Created on Jan 10, 2009, 5:34:13 PM
 */
package com.dksoft.view;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;
import org.apache.log4j.Logger;

/**
 *
 * @author Dickson
 * Create a date dialog box to enter date to display / highlight in MonthCalendar
 * @param parent
 * @param modal
 */
public class DateDialog extends JDialog implements KeyListener {

    private static Logger logger = Logger.getLogger(DateDialog.class.getName());
    private static MaskFormatter formatter;
    private static GregorianCalendar gc = new GregorianCalendar();
    private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");

    public DateDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        preInitComponent();
        initComponents();
        postInitComponent();
    }

    /**
     * preInitComponent using Key event instead of formatter.setValidCharacters
     * because formatter will restrict user to input numeric when placeHolder is set to character.
     * If you want to allow user to input number at the first place, your placeHolder must put # or
     * somthing else which is numeric instead of character like DD-MM-YYYY
     */
    private void preInitComponent() {
        try {
            formatter = new MaskFormatter("**-**-****");
            formatter.setPlaceholder("DD-MM-YYYY");
//          formatter.setValidCharacters("0123456789");
        } catch (ParseException ex) {
            logger.debug("preInitComponent Fail: " + ex.toString());
        }
    }

    private void postInitComponent() {
        txtDate.addKeyListener(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtDate = new JFormattedTextField(formatter);
        lblGoto = new javax.swing.JLabel();
        btnOk = new javax.swing.JButton();
        lblEgDate = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Goto");
        setResizable(false);

        lblGoto.setText("Goto");

        btnOk.setText("OK");
        btnOk.setRequestFocusEnabled(false);
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        lblEgDate.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
        lblEgDate.setText("(eg: 31-12-2000)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblGoto)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(lblEgDate, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnOk)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblGoto)
                    .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnOk))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblEgDate)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        performSetDate();
    }//GEN-LAST:event_btnOkActionPerformed

    private void performSetDate() {
        if (Integer.parseInt(txtDate.getText().substring(6, 10)) < 2009) { // since this reminder start in year 2009
            JOptionPane.showMessageDialog(this, "Please enter year greater than 2009!", "Error", JOptionPane.ERROR_MESSAGE);
            txtDate.setText("DD-MM-YYYY");
            txtDate.setCaretPosition(0);
        } else {
            gc.setLenient(false);        // must do this
            try {
                gc.set(GregorianCalendar.YEAR, Integer.parseInt(txtDate.getText().substring(6, 10)));
                gc.set(GregorianCalendar.MONTH, Integer.parseInt(txtDate.getText().substring(3, 5)) - 1);
                gc.set(GregorianCalendar.DATE, Integer.parseInt(txtDate.getText().substring(0, 2)));
                firePropertyChange("dayChangeFromDateDialog", null, sdf.format(gc.getTime()));
                logger.info("[performSetDate]: date set= " + sdf.format(gc.getTime()));
                this.dispose();
            } catch (Exception e) {
                getToolkit().beep();
                JOptionPane.showMessageDialog(this, "Wrong date!", "Error", JOptionPane.ERROR_MESSAGE);
                txtDate.setText("DD-MM-YYYY");
                txtDate.setCaretPosition(0);
                logger.debug("performSetDate Fail: " + e.toString());
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DateDialog dialog = new DateDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnOk;
    private javax.swing.JLabel lblEgDate;
    private javax.swing.JLabel lblGoto;
    private javax.swing.JFormattedTextField txtDate;
    // End of variables declaration//GEN-END:variables

    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        if (c == KeyEvent.VK_ENTER) performSetDate();

        else if(c == KeyEvent.VK_ESCAPE) this.dispose();

        else if (!((Character.isDigit(c) ||
                (c == KeyEvent.VK_BACK_SPACE) ||
                (c == KeyEvent.VK_DELETE)))) {
            getToolkit().beep();
            e.consume();
        }
        
    }

    public void keyPressed(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }
}
